<template>
  <div>
    <el-page-header @back="$router.back(-1)" content="虚拟设备详情">
    </el-page-header>
    <el-divider></el-divider>
    <el-form :inline="true" label-width="80px">
      <el-form-item label="名称:">
        {{ detail.name }}
      </el-form-item>
      <el-form-item label="产品:">
        {{ detail.productKey }}
      </el-form-item>
      <el-form-item label="类型:">
        {{ typeName[detail.type] }}
      </el-form-item>
      <el-form-item label="状态:">
        <el-button
          v-if="detail.state == 'running'"
          type="success"
          size="mini"
          plain
          @click="setState(detail.id, 'stopped')"
          >运行中</el-button
        >
        <el-button
          v-if="detail.state == 'stopped'"
          type="danger"
          size="mini"
          plain
          @click="setState(detail.id, 'running')"
          >已停止</el-button
        >
      </el-form-item>
      <el-form-item label=" ">
        <el-button @click="run" size="mini">立即执行</el-button>
      </el-form-item>
    </el-form>
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="绑定设备" name="config">
        <el-row>
          <el-col :span="12">
            <DeviceSelector
              v-if="params.pk"
              :showDeviceId="true"
              :showProduct="false"
              :param="params"
              @deviceSelected="onDeviceSelected"
            ></DeviceSelector
          ></el-col>
          <el-col :span="12" style="padding: 0 10px">
            <div style="padding-top: 30px">已绑定：</div>
            <el-table
              size="small"
              :data="bindDevices"
              highlight-current-row
              v-loading="$store.state.loading"
              border
              element-loading-text="拼命加载中"
            >
              <el-table-column sortable label="设备ID">
                <template slot-scope="scope">
                  {{ scope.row }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    @click="handleDelBind(scope.$index, scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="脚本" name="script">
        <div>new (function () {</div>
        <ScriptEditor v-if="this.showScript" :code="detail"></ScriptEditor>
        <div>})()</div>
        <div style="margin-top: 30px"></div>
        <el-button type="primary" @click="saveScript" size="small"
          >保存</el-button
        >
      </el-tab-pane>
      <el-tab-pane label="日志" name="log">
        <el-table
          size="small"
          :data="logs"
          highlight-current-row
          v-loading="$store.state.loading"
          border
          element-loading-text="拼命加载中"
          style="width: 100%"
        >
          <el-table-column align="center" type="index" width="60">
          </el-table-column>
          <el-table-column
            sortable
            prop="logAt"
            label="时间"
            width="250"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <div>{{ scope.row.logAt | timestampToTime }}</div>
            </template>
          </el-table-column>
          <el-table-column
            sortable
            prop="result"
            label="结果"
            width="300"
            show-overflow-tooltip
          >
          </el-table-column>
          <Pagination :data="formInline" @onPagePaging="getLogs"></Pagination>
        </el-table>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import {
  VirtualDeviceDetail,
  VirtualDeviceSaveDevices,
  VirtualDeviceSaveScript,
  VirtualDeviceSetState,
  VirtualDeviceRun,
  VirtualDeviceLogList,
} from "@/api/deviceApi";
import DeviceSelector from "@/views/device/DeviceSelector.vue";
import ScriptEditor from "@/components/ScriptEditor.vue";
import Pagination from "../../components/Pagination";
export default {
  data() {
    return {
      loading: false,
      activeName: "config",
      title: "",
      id: "",
      bindDevices: [],
      formInline: {
        page: 1,
        size: 10,
        total: 0,
        id: "",
      },
      detail: {},
      params: {
        pk: "",
      },
      logs: [],
      showScript: false,
      typeName: {
        thingModel: "基于物模型",
        protocol: "基于设备协议",
      },
      triggerName: {
        none: "无（手动）",
        cron: "定时执行",
        random: "随机执行",
      },
    };
  },
  components: { DeviceSelector, ScriptEditor, Pagination },
  created() {
    this.getdata();
    this.getLogs();
  },
  methods: {
    getdata() {
      this.id = this.$route.query.id;
      this.formInline.id = this.id;
      VirtualDeviceDetail(this.id).then((res) => {
        this.bindDevices = res.devices || [];
        this.detail = res;
        this.params.pk = res.productKey;
      });
    },
    onDeviceSelected: function (device) {
      if (
        this.bindDevices.findIndex((d) => {
          return d == device.deviceId;
        }) >= 0
      ) {
        return;
      }
      this.bindDevices.push(device.id);
      this.saveDevices();
    },
    handleDelBind(index) {
      this.bindDevices.splice(index, 1);
      this.saveDevices();
    },
    saveDevices() {
      VirtualDeviceSaveDevices(this.id, this.bindDevices).then(() => {
        this.$notify({
          title: "成功",
          message: "保存成功",
          type: "success",
        });
      });
    },
    handleClick(tab) {
      this.showScript = tab.name == "script";
      if (tab.name == "log") {
        this.getLogs();
      }
    },
    setState(id, state) {
      VirtualDeviceSetState({ id: id, state: state }).then(() => {
        this.getdata();
      });
    },
    saveScript() {
      VirtualDeviceSaveScript(this.id, this.detail.script).then(() => {
        this.$notify({
          title: "成功",
          message: "保存成功",
          type: "success",
        });
      });
    },
    run() {
      VirtualDeviceRun(this.id).then(() => {
        this.$notify({
          title: "成功",
          message: "执行成功",
          type: "success",
        });
        this.getLogs();
      });
    },
    getLogs() {
      VirtualDeviceLogList(this.formInline).then((res) => {
        this.logs = res.data;
        this.formInline.total = res.total;
      });
    },
  },
};
</script>